package com.douguo.recipe;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.douguo.recipe.network.Constant;
import com.douguo.recipe.network.GetEkArticleList;
import com.douguo.recipe.network.GetPhoto;
import com.douguo.recipe.network.GetRecipe;
import com.douguo.recipe.network.GetRecipeList;
import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.Caipu;
import com.douguo.recipe.provider.DBHelper;
import com.douguo.recipe.view.NavigationView;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.SimpleAdapter.ViewBinder;

public class RecipelistActivity extends DouguoActivity {

	private static final String TAG = "RecipelistActivity";
	
	public static final int MSG_UPDATE_LIST_FROM_NETWORK = 0;
	public static final int MSG_UPDATE_LIST_FROM_DATABASE = 1;
	public static final int MSG_UPDATE_TITLE = 2;// update the title
	public static final int MSG_UPDATE_PHOTO = 3;

	// ------------ui-------------
//	private Button nextTenBtn;
	private ViewGroup nextTenDownloading;
	private View foot;
	private View retryView;
	private View nextTenView;
	private ListView lv;
	private NavigationView mNavigation;
	private Button mBtnBack;
	// ---------------------------

	// -----------data------------
	List<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
	private int startPos;
	private static final int PAGESIZE = 10;
	private static final int MAX_RETRY_TIMES = 1;
	private int currentRetryTimes;
	private boolean isAutoDownloadThumb;
	private boolean isToLoad;
	private boolean isScrolling;
	private String title;
	// private int[] types;
	// private String[] ids;
	// ---------------------------

	// -----------bundle----------
	private int[] types;
	private String[] ids;
	private String keywords;
	// ---------------------------

	// ----------adatper----------
	RecipeListAdapter listItemAdapter;
	// ---------------------------

	// ---------strings-----------
	private static String static_recipe_author;
	private static String static_recipe_major;
	private static String static_recipe_minor;
	private static boolean mInitFlag;
	// ---------------------------

	// ---------helper------------
	private static DBHelper dbHelper;
	// ---------------------------

	private static final int MENU_HOME = Menu.FIRST;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			boolean mFromDBFlag = false;
			switch (msg.what) {
			case MSG_UPDATE_LIST_FROM_DATABASE:
				mFromDBFlag = true;
			case MSG_UPDATE_LIST_FROM_NETWORK: {

				List<Caipu> recipes = (List<Caipu>) msg.obj;
				if (recipes != null) {
					foot.findViewById(R.id.noRecipe).setVisibility(
							View.GONE);
					foot.findViewById(R.id.nextTenRecipesLoading)
							.setVisibility(View.GONE);
					foot.findViewById(R.id.nextTenRecipes).setVisibility(
							View.GONE);
					if (recipes.size() == 0 && listItem.size() == 0) {
						foot.setVisibility(View.VISIBLE);
						foot.findViewById(R.id.noRecipe).setVisibility(
								View.VISIBLE);

						return;
					}
					if (recipes.size() < PAGESIZE) {
						foot.setVisibility(View.GONE);
						lv.removeFooterView(foot);
					} else {
						foot.findViewById(R.id.nextTenRecipes).setVisibility(
								View.VISIBLE);
//						nextTenBtn.setVisibility(View.VISIBLE);
						if (!mFromDBFlag)
							isToLoad = true;
					}

					for (Caipu caipu : recipes) {
						HashMap<String, Object> item = new HashMap<String, Object>();
						item.put("id", caipu.id);
						item.put("name", caipu.name);
						// item.put("thumnb", R.drawable.gallery1);
						item.put("author", static_recipe_author + ": "
								+ caipu.author);
						item.put("major", static_recipe_major + ": "
								+ caipu.major);
						item.put("minor", static_recipe_minor + ": "
								+ caipu.minor);
						item.put("retry", 0);
						item.put("thumnbLoaded",Boolean.FALSE);
						item.put("thumnbPath", caipu.thumbPath);
						if (isAutoDownloadThumb) {
							item.put("thumnb", BitmapFactory.decodeResource(
									getResources(),
									R.drawable.cookdefault80_downloading));
						} else {
							item.put("thumnb", BitmapFactory.decodeResource(
									getResources(), R.drawable.cookdefault80));
						}
						listItem.add(item);

						if (msg.what == MSG_UPDATE_LIST_FROM_NETWORK
								&& isAutoDownloadThumb) {
							// GetPhoto.getPhoto(listItem.size() - 1,
							// caipu.picPath, mHandler);
							item.put("useNetwork", Boolean.TRUE);
							item.put("gettingImg", Boolean.FALSE);
							item.put("recipePicPath", caipu.thumbPath);

							
						} else if (msg.what == MSG_UPDATE_LIST_FROM_DATABASE) {
							Bitmap bm = Util
									.read80X80BitmapFromSDCard(caipu.thumbPath);
							// TODO if bitmap is null
							if (bm != null) {
								item.put("thumnb", bm);
							} else {
								item.put("thumnb", BitmapFactory
										.decodeResource(getResources(),
												R.drawable.cookdefault80));
							}
						}
					}
					//
				} else if (recipes == null
						&& currentRetryTimes++ < MAX_RETRY_TIMES) {// retry
					showList();
				} else {
					retryView.setVisibility(View.VISIBLE);
					nextTenDownloading.setVisibility(View.GONE);
				}
				//
				// nextTenDownloading.setVisibility(View.GONE);
				// if(listItem.size() - startPos >= PAGESIZE){
				// nextTenBtn.setVisibility(View.VISIBLE);
				// }
				startPos = listItem.size();
				listItemAdapter.notifyDataSetChanged();

				break;
			}
			case MSG_UPDATE_TITLE: {
				String title = (String) msg.obj;

				break;
			}
			case Constant.GET_PHOTO: {
				int pos = msg.arg1;
				SoftReference<Bitmap> refBitmap = (SoftReference<Bitmap>) msg.obj;
				HashMap<String, Object> hm = listItem.get(pos);
				int retryTimes = (Integer) hm.get("retry");
				String thunmbPath = (String) hm.get("thumnbPath");
				if (refBitmap != null) {
					Bitmap bitmap = refBitmap.get();
					if (bitmap != null) {
						hm.put("thumnb", bitmap);
						hm.put("thumnbLoaded",Boolean.TRUE);
						listItemAdapter.notifyDataSetChanged();
					}

				} else if (refBitmap == null && retryTimes < MAX_RETRY_TIMES) {
					hm.put("retry", ++retryTimes);
					GetPhoto.getPhoto(pos, thunmbPath, mHandler);
				}

				break;
			}
			}
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.recipelist);
		currentRetryTimes = 0;
		startPos = 0;
		dbHelper = new DBHelper(this);
		if (Util.updateNetworkType(this)) {
			if (!Util.isUseNetworkPreferences(this)
					|| Util.networkInfoString.equals(Util.NETWORK_NONETWORK)) {
				Util.showShortToast(this, R.string.showOfflineData);
			} else {
				Util.showShortToast(this, R.string.showOnlineData);
			}
		}
		isAutoDownloadThumb = Util.isDownloadPhotoPreferences(this);
		isToLoad = true;
		isScrolling = false;
		initBundle();
		initUI();

		initStrings();
	}

	private void initListFoot() {
		LayoutInflater inflater = LayoutInflater.from(this);
		foot = inflater.inflate(R.layout.recipelist_footer, null);
		nextTenView = (LinearLayout) foot.findViewById(R.id.nextTenRecipes);
		nextTenDownloading = (ViewGroup) foot
				.findViewById(R.id.nextTenRecipesLoading);
		retryView = foot.findViewById(R.id.retryView);
		Button retryBtn = (Button) retryView.findViewById(R.id.btnRetry);
		retryBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				startPos = 0;
				showList();
			}
		});
//		nextTenBtnLayout.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				// nextTenDownloading.setVisibility(View.VISIBLE);
//				// nextTenBtn.setVisibility(View.GONE);
//				// // startPos += 10;
//				// GetRecipeList.getCaipuList(GetRecipeList.ACTION_GET_CAIXI_LIST,null,startPos,PAGESIZE,mHandler);
//				showList();
//			}
//		});
		foot.setTag("foot");
		lv.addFooterView(foot);
	}

	private void initUI() {
		lv = (ListView) findViewById(R.id.recipeslist);

		listItemAdapter = new RecipeListAdapter(this,
				listItem,// 鏁版嵁婧�
				R.layout.recipelist_listitem,// ListItem鐨刋ML瀹炵幇
				new String[] { "thumnb", "name", "author", "major", "minor" },
				new int[] { R.id.recipeImg, R.id.recipeName, R.id.recipeAuthor,
						R.id.recipeMajor, R.id.recipeMinor });
		listItemAdapter.setViewBinder(new ViewBinder() {

			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (view instanceof TextView) {
					TextView tv = (TextView) view;
					tv.setText(textRepresentation);
				} else if (view instanceof ImageView) {
					ImageView img = (ImageView) view;
					img.setImageBitmap((Bitmap) data);
					// img.setImageResource(R.drawable.gallery1);
				}
				return true;// must be true
			}

		});
		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> adapterView, View view, int pos,
					long id) {
				if(adapterView.getAdapter().getItemViewType(pos) != AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER){
					Intent intent = new Intent(RecipelistActivity.this,
							RecipeActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("recipeId",
							(String) listItem.get(pos).get("id"));
					bundle.putInt("pos", pos);
					int[] ids = new int[listItem.size()];
					int i = 0;
					for (; i < listItem.size(); ++i) {
						ids[i] = Integer
								.valueOf((String) listItem.get(i).get("id"));
					}
					bundle.putIntArray("ids", ids);
					intent.putExtras(bundle);
					startActivity(intent);
				}
				else {
					 if(nextTenView != null && nextTenView.getVisibility() == View.VISIBLE){//下十个文章按钮可见
						showList();
					 }
				}
			}
		});

		if (keywords != null && keywords.length() > 0) {
			mNavigation = new NavigationView(this, NavigationView.STATE_SEARCH);
			setTitle(getString(R.string.titleSouSuoJieGuo));
		} else {
			mNavigation = new NavigationView(this, NavigationView.STATE_SORT);
			setTitle(title);
		}
		mBtnBack = (Button) findViewById(R.id.imageButton_back);
		mBtnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
		initListFoot();

		
		lv.setOnScrollListener(new OnScrollListener() {

			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_FLING:
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					// mBtnBack.setText("busy");
					isScrolling = true;
					break;
				case OnScrollListener.SCROLL_STATE_IDLE:
					// mBtnBack.setText("not busy");
					int first = view.getFirstVisiblePosition();
					int count = view.getChildCount();
					for (int i = 0; i < count; i++) {
						if (!(listItemAdapter.getItemViewType(first + i) == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
							getPhoto(first + i);
						}

					}
					isScrolling = false;
					break;
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
//				if (isToLoad
//						&& totalItemCount - firstVisibleItem == visibleItemCount) {
//					showList();
//				}
				if(view.getLastVisiblePosition()==view.getCount()-1){
					isScrolling = false;
				}

			}
		});
		showList();
		lv.setAdapter(listItemAdapter);
		
	}

	private void getPhoto(int position) {
		Map map = (Map) listItemAdapter.getItem(position);

		if (map.containsKey("useNetwork")
				&& map.get("useNetwork") == Boolean.TRUE
				&& ((!map.containsKey("gettingImg") || map.get("gettingImg") == Boolean.FALSE)) && map.get("thumnbLoaded") == Boolean.FALSE) {
			GetPhoto.getPhoto(position, (String) map.get("recipePicPath"),
					mHandler);
			map.put("gettingImg", Boolean.TRUE);
		}
	}

	private void initStrings() {
		if (!mInitFlag) {
			static_recipe_author = this.getResources().getString(
					R.string.author);
			static_recipe_major = this.getResources().getString(R.string.major);
			static_recipe_minor = this.getResources().getString(R.string.minor);
			mInitFlag = true;
		}
	}

	private void initBundle() {
		Bundle bundle = getIntent().getExtras();
		types = bundle.getIntArray("types");
		ids = bundle.getStringArray("ids");
//		for(String id:ids ){
//			Log.d(TAG, "id:"+id);
//		}
		// get and process search query here
		final Intent queryIntent = getIntent();
		final String queryAction = queryIntent.getAction();
		if (Intent.ACTION_SEARCH.equals(queryAction)) {
			keywords = queryIntent.getStringExtra(SearchManager.QUERY);
		}
		title= bundle.getString("title");

	}

	private void showList() {
		isToLoad = false;
		if (Util.networkInfoString.equals(Util.NETWORK_NONETWORK)
				|| !Util.isUseNetworkPreferences(this)) {
			showListFromDatabase();
		} else {
			showListFromNetWork();
		}
	}

	private void showListFromDatabase() {
		List<Caipu> recipes = dbHelper.getRecipeList(types, ids, keywords);
		mHandler.sendMessage(mHandler.obtainMessage(
				MSG_UPDATE_LIST_FROM_DATABASE, recipes));
		foot.setVisibility(View.INVISIBLE);
		if (recipes.size() > 0) {
			lv.removeFooterView(foot);
		}
	}

	private void showListFromNetWork() {
		GetRecipeList.getCaipuList(types, ids, keywords, startPos, PAGESIZE,
				mHandler);
		nextTenDownloading.setVisibility(View.VISIBLE);
		nextTenView.setVisibility(View.GONE);
		retryView.setVisibility(View.GONE);

	}

	private class RecipeListAdapter extends SimpleAdapter {

		public RecipeListAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
			// TODO Auto-generated constructor stub
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			if(!isScrolling){
				getPhoto(position);
			}
			return view;
		}

		@Override
		public int getItemViewType(int position) {
			return position >= getCount() || position < 0 ? AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER
					: 0;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_HOME, 0, R.string.backToHome);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_HOME:
			Intent homeIntent = new Intent(this, HomeActivity.class);
			homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(homeIntent);
			break;
		}
		return true;

	}

}
